import json

from django.http import JsonResponse
from functools import wraps


class FlagException(Exception):
    def __init__(self, flag, code, error_msg, **kwargs):
        self.flag = flag
        self.code = code
        self.errorMsg = error_msg
        if kwargs:
            self.data = kwargs

    def to_dict(self):
        ret = {}
        ret.update(self.__dict__)
        if hasattr(self, 'data'):
            ret.update(self.data)
        #return json.dumps(ret, ensure_ascii=False)
        return ret


def json_response(func):
    @wraps(func)
    def wrapper(me_instance, request, *args, **kwargs):
        ret = {'flag': True, 'code': 0, 'errorMsg': '操作成功'}

        try:
            data = func(me_instance, request, *args, **kwargs)
            if data:
                if isinstance(data, dict):
                    ret.update(data)
                elif isinstance(data, list):
                    ret.setdefault('data', data)

            return JsonResponse(ret, status=200)
        except FlagException as e:
            # ret['flag'] = False
            # ret['code'] = 80000
            # ret['errorMsg'] = e.__repr__()
            return JsonResponse(e.to_dict(), status=200)
    return wrapper
